package com.common.app.db

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.common.app.data.bean.BaseCityModel
import com.common.app.data.bean.CloudDownDataModel
import com.common.app.data.bean.SearchHistoryModel
import com.common.base.utils.AppUtils

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/21
 * <p>
 * 描述：room数据库
 * <p>
 * 修订历史：
 */
@Database(
    entities = [ReportEvent::class, SearchHistoryModel::class, BaseCityModel::class, CloudDownDataModel::class],
    version = 1
)//添表升级
abstract class AppDataBase : RoomDatabase() {
    companion object {
        private val mDataBase: AppDataBase by lazy {
            Room.databaseBuilder(AppUtils.getContext(), AppDataBase::class.java, "gs_sanotrive.db")
                .allowMainThreadQueries() //允许在主线程中查询
//                //数据库升级异常之后的回滚并删除老数据，自动根据版本号数据库升级，升级时会删除老数据
//                .fallbackToDestructiveMigration()
//                //数据库升级异常后根据指定版本进行回滚
//                .fallbackToDestructiveMigrationFrom()
//                //手动升级数据库的入口（如果没有配置升级的时候会将数据库内容全部清除）
//                .addMigrations(MIGRATION_1_2,MIGRATION_2_3,MIGRATION_3_4)
                .build()
        }

        fun getDb(): AppDataBase = mDataBase

        private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "CREATE TABLE IF NOT EXISTS search_history (searchKey TEXT,"
                            + "startTime INTEGER NOT NULL DEFAULT 0,"
                            + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)"
                )

            }
        }

        private val MIGRATION_2_3: Migration = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "CREATE TABLE IF NOT EXISTS history_account (mPhone TEXT,"
                            + "mNikeName TEXT,"
                            + "headUrl TEXT,"
                            + "customExt TEXT,"
                            + "createdTime INTEGER NOT NULL DEFAULT 0,"
                            + "status INTEGER NOT NULL DEFAULT 0,"
                            + "mCountry TEXT,"
                            + "userId TEXT,"
                            + "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL)"
                )

            }
        }
        private val MIGRATION_3_4 = object : Migration(3, 4) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 执行删除表的 SQL 语句
                database.execSQL("DROP TABLE IF EXISTS history_account")
            }
        }
        private val MIGRATION_2_4: Migration = object : Migration(2, 4) {//2升到4操作
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "CREATE TABLE IF NOT EXISTS new_history_account (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                            "userId TEXT, mPhone TEXT, mPwd TEXT, mCountry TEXT, mNikeName TEXT, headUrl TEXT, " +
                            "customExt TEXT, createdTime INTEGER NOT NULL DEFAULT 0, status INTEGER NOT NULL DEFAULT 0)"
                )
            // Check if old table exists
            val cursor = database.query("PRAGMA table_info(history_account)")
            val tableExists = cursor.count > 0
            cursor.close()

            if (tableExists) {

                // Copy data from old table to new table
                database.execSQL("INSERT INTO new_history_account (id, userId, mPhone, mPwd, mCountry, mNikeName, headUrl, " +
                        "customExt, createdTime, status) SELECT id, userId, mPhone, '', mCountry, mNikeName, headUrl, " +
                        "customExt, createdTime, status FROM history_account")

//                // 删除旧表 history_account
//                database.execSQL("DROP TABLE history_account")
            }

            }
        }
    }

    abstract fun getReportEventDao(): ReportEventDao
    abstract fun getSearchHistoryDao(): SearchHistoryModelDao
    abstract fun getSearchCityModelDao(): SearchCityModelDao
    abstract fun getCloudDownDataDao(): CloudDownDataDao
}